<template>
  <el-card>
    <div slot="header">
      <span>分配权限</span>
    </div>
    <el-tree
      :data="menus"
      :props="defaultProps"
      node-key="id"
      show-checkbox
      default-expand-all
      :default-checked-keys="selectMenus"
      ref="trees"
    ></el-tree>
    <div class="btn_">
      <el-button type="primary" @click="saveMenu">保存</el-button>
      <el-button @click="clearMenu">清空</el-button>
    </div>
  </el-card>
</template>

<script lang="ts">
import { allocateRoleMenus, DataArray, getMenuNodeList, getRoleMenus } from '@/services/menu'
import { Tree } from 'element-ui'
import Vue from 'vue'
export default Vue.extend({
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      selectMenus: []
    }
  },
  created () {
    this.loadMenuNodeList()
    this.loadRoleMenus()
  },
  methods: {
    async loadMenuNodeList () {
      const { data } = await getMenuNodeList()
      this.menus = data.data as DataArray[] | any
    },
    async loadRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      // console.log('选中', data)
      this.checkSelectData(data.data)
      // console.log('选中了', this.selectMenus)
    },
    checkSelectData (menus:any) {
      menus.forEach((menu:any) => {
        if (
          (menu.selected && menu.parentId === -1 && !menu.subMenuList) ||
          (menu.selected && menu.parentId !== -1)
        ) {
          this.selectMenus.push(menu.id as never)
          this.$nextTick(() => {
            if (this.$refs.trees) {
              (this.$refs.trees as Tree).setCheckedKeys(this.selectMenus)
            }
          })
          // this.selectMenus = [...this.selectMenus, menu.id] as any
        }
        if (menu.subMenuList) {
          this.checkSelectData(menu.subMenuList)
        }
      })
    },
    async saveMenu () {
      // tree的方法，用于获取被选中节点的key
      // 上面的key 就是 dom 中 node-key 设置的 id
      const menuIdList = (this.$refs.trees as Tree).getCheckedKeys()
      const { data } = await allocateRoleMenus({
        roleId: this.roleId as number,
        menuIdList
      })
      if (data.code === '000000') {
        this.$router.push('/role')
      }
    },
    clearMenu () {
      (this.$refs.trees as Tree).setCheckedKeys([])
    }
  }
  // mounted () {

  // }
})
</script>

<style lang="scss" scoped>
.btn_{
  margin-top:2rem;
  display: flex;
  justify-content: center;
}
</style>
